package com.linh.web.spring;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.hibernate.cfg.Environment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.linh.web.env.Database;

@Configuration
public class MySqlSpring extends DatabaseSpring {
	static final String MYSQL_DRIVER_CLASS="com.mysql.jdbc.Driver";

	@Autowired
	Database database;

	@Override
	@Bean
	org.hibernate.cfg.Configuration configuration() {
		org.hibernate.cfg.Configuration configuration = new org.hibernate.cfg.Configuration();
		configuration.setProperty(Environment.DRIVER, MYSQL_DRIVER_CLASS);
		configuration.setProperty(Environment.USER, database.getUserName());
		configuration.setProperty(Environment.URL, database.getJdbcUrl());
		configuration.setProperty(Environment.PASS, database.getPassword());
		configuration.setProperty(Environment.DIALECT, hibernateDialect());
		for(Class<?> klass:domainClasses()){
			configuration.addAnnotatedClass(klass);
		}
		return configuration;
	}

	@Override
	DataSource dataSource() {
		BasicDataSource basicDataSource = new BasicDataSource();
		basicDataSource.setDriverClassName(MYSQL_DRIVER_CLASS);
		basicDataSource.setUrl(database.getJdbcUrl());
		basicDataSource.setUsername(database.getUserName());
		basicDataSource.setPassword(database.getPassword());
		configureDataSource(basicDataSource);
		return basicDataSource;
	}

	@Override
	String hibernateDialect() {
		return "org.hibernate.dialect.MySQL5Dialect";
	}

}
